package com.tenement.service.impl;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tenement.entity.Suggest;
import com.tenement.mapper.SuggestMapper;
import com.tenement.service.SuggestService;
import com.tenement.vo.QueryVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import static com.tenement.entity.table.SuggestTableDef.SUGGEST;
import static com.tenement.entity.table.UserTableDef.USER;

/**
 *  服务层实现。
 *
 * @author BertXie
 * @since 1.0.1
 */
@Service
@RequiredArgsConstructor
public class SuggestServiceImpl extends ServiceImpl<SuggestMapper, Suggest> implements SuggestService {

    private final SuggestMapper suggestMapper;

    @Override
    public boolean feedback(Suggest suggest) {
        return UpdateChain.of(Suggest.class)
                .set(SUGGEST.ANSWER, suggest.getAnswer())
                .set(SUGGEST.STATUS, 1)
                .set(SUGGEST.ANSWER_USER_ID, suggest.getAnswerUserId())
                .where(SUGGEST.ID.eq(suggest.getId()))
                .update();
    }

    @Override
    public Page<Suggest> list(QueryVo queryVo) {
        QueryWrapper wrapper = QueryWrapper.create().from(SUGGEST)
                .select(
                        SUGGEST.ID, SUGGEST.ISSUE,
                        SUGGEST.ANSWER, SUGGEST.STATUS,
                        SUGGEST.ISSUE_USER_ID, SUGGEST.ANSWER_USER_ID,
                        SUGGEST.TENEMENT_ID, SUGGEST.TYPE,
                        SUGGEST.PHONE,SUGGEST.TITLE,USER.ID,
                        USER.NAME,USER.REAL_NAME,USER.PHONE_NUMBER
                )
                .leftJoin(USER).on(USER.ID.in(SUGGEST.ISSUE_USER_ID,SUGGEST.ANSWER_USER_ID))
                .where(
                        SUGGEST.ISSUE.eq(queryVo.getKeyWord(), StrUtil.isNotEmpty(queryVo.getKeyWord()))
                                .or(SUGGEST.ANSWER.eq(queryVo.getKeyWord(), StrUtil.isNotEmpty(queryVo.getKeyWord())))
                )
                .and(SUGGEST.STATUS.eq(queryVo.getStatus(), queryVo.getStatus() != -1))
                .and(SUGGEST.ISSUE_USER_ID.eq(queryVo.getUniKey(), queryVo.getUniKey() != -1L));
        return suggestMapper.paginate(queryVo.getPage(),queryVo.getSize(),wrapper);
    }
}
